package cn.hznc.controller.process;

import cn.hznc.aspect.BusinessType;
import cn.hznc.aspect.Log;
import cn.hznc.controller.process.strategy.AbutmentProcessContext;
import cn.hznc.controller.process.strategy.ZccAbutmentProcessStrategy;
import cn.hznc.domain.entity.AllotEmployeeEntity;
import cn.hznc.domain.entity.ProcessCraftEntity;
import cn.hznc.domain.entity.ProcessEntity;
import cn.hznc.domain.request.process.*;
import cn.hznc.domain.request.production.PucAndProConnectReq;
import cn.hznc.domain.request.schedule.MachineToolChildReq;
import cn.hznc.domain.response.PageResult;
import cn.hznc.domain.response.ResponseBody;
import cn.hznc.dto.AllotEmployeeImport;
import cn.hznc.excel.AllotEmployeeReadListener;
import cn.hznc.exception.SystemException;
import cn.hznc.exception.ToolManageException;
import cn.hznc.controller.service.process.ProcessManageService;
import cn.hznc.permission.Permission;
import cn.hznc.utils.CommonUtil;
import cn.hznc.utils.FileUploadUtil;
import cn.hznc.utils.FileUtils;
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 工序管理接口
 *
 * @Author Administrator
 * @Date 2023/3/13 16:02
 */
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/process")
@Slf4j
public class ProcessManageController {

    @Resource
    private ProcessManageService processManageService;

    @Resource
    private ZccAbutmentProcessStrategy zccAbutmentProcessStrategy;


    /**
     * 工序查询(分页)
     *
     * @param queryProcessReq queryProcessReq
     * @return
     */
    @RequestMapping(value = "/queryProcessList", method = RequestMethod.POST)
    public ResponseBody<PageResult<ProcessEntity>> queryProcessList(@RequestBody QueryProcessReq queryProcessReq) {
        return ResponseBody.success(processManageService.queryProcessList(queryProcessReq));
    }

    /**
     * 工序修改与新增
     *
     * @param addOrEditProcessReq addOrEditProcessReq
     * @return
     */
    @RequestMapping(value = "/addOrEditProcess", method = RequestMethod.POST)
    @Log(title = "新增或修改工艺", businessType = BusinessType.UPDATE)
    public ResponseBody<Boolean> addOrEditProcess(@RequestBody AddOrEditProcessReq addOrEditProcessReq) {
        try {
            processManageService.addOrEditProcess(addOrEditProcessReq);
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
        return ResponseBody.success(Boolean.TRUE);
    }

    /**
     * 工序删除
     *
     * @param deleteProcessReq deleteProcessReq
     * @return
     */
    @RequestMapping(value = "/deleteProcess", method = RequestMethod.POST)
    @Log(title = "删除工艺", businessType = BusinessType.DELETE)
    public ResponseBody<Boolean> deleteProcess(@RequestBody DeleteProcessReq deleteProcessReq) {
        return ResponseBody.success(processManageService.deleteProcess(deleteProcessReq));
    }


    /**
     * 查询工艺详情（通过图号查询）
     *
     * @param queryCraftDetailReq deleteProcessReq
     * @return
     */
    @RequestMapping(value = "/queryCraftDetail", method = RequestMethod.POST)
    public ResponseBody<List<ProcessCraftEntity>> queryCraftDetail(@RequestBody QueryCraftDetailReq queryCraftDetailReq) {
        return ResponseBody.success(processManageService.queryCraftDetail(queryCraftDetailReq));
    }

//    /**
//     * 查询物料详情（通过图号查询）
//     *
//     * @param queryBomDetailReq queryBomDetailReq
//     * @return
//     */
//    @RequestMapping(value = "/queryBomDetail", method = RequestMethod.POST)
//    public ResponseBody<List<ProcessBomEntity>> queryBomDetail(@RequestBody QueryBomDetailReq queryBomDetailReq) {
//        return ResponseBody.success(processManageService.queryBomDetail(queryBomDetailReq));
//    }

    /**
     * 根据产品号查询工序内码
     *
     * @return
     */
    @RequestMapping(value = "/queryCodeByFigureNo", method = RequestMethod.GET)
    public ResponseBody queryCodeByFigureNo(@RequestParam("materialNo") String materialNo) {
        try {
            return ResponseBody.success(processManageService.queryCodeByFigureNo(materialNo));
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
    }


    /**
     * 新增修改删除工艺
     *
     * @param operateCraftReq operateCraftReq
     * @return
     */
    @RequestMapping(value = "/editOrAddCraft", method = RequestMethod.POST)
    @Log(title = "新增或编辑工序", businessType = BusinessType.OTHER)
    public ResponseBody<Boolean> editOrAddCraft(@RequestBody OperateCraftReq operateCraftReq) {
        try {
            processManageService.editOrAddCraft(operateCraftReq);
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
        return ResponseBody.success(Boolean.TRUE);
    }

    /**
     * 工艺状态设置
     *
     * @return
     */
    @RequestMapping(value = "/setProcessStatus", method = RequestMethod.POST)
    @Log(title = "编辑工艺完成状态", businessType = BusinessType.UPDATE)
    public ResponseBody<Boolean> setProcessStatus(@RequestBody SetProcessStatusReq setProcessStatusReq) {
        try {
            processManageService.setProcessStatus(setProcessStatusReq);
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
        return ResponseBody.success(Boolean.TRUE);
    }

//    /**
//     * 新增修改删除物料
//     *
//     * @param operateBomReq operateBomReq
//     * @return
//     */
//    @RequestMapping(value = "/editOrAddBom", method = RequestMethod.POST)
//    public ResponseBody<Boolean> editOrAddBom(@RequestBody OperateBomReq operateBomReq) {
//        try {
//            processManageService.editOrAddBom(operateBomReq);
//        } catch (ToolManageException te) {
//            return ResponseBody.error(te.getCode(), te.getMsg());
//        }
//        return ResponseBody.success(Boolean.TRUE);
//    }

    /**
     * 关联主程序（多余接口）
     *
     * @param connectReq connectReq
     * @return
     */
    @RequestMapping(value = "/connectProgram", method = RequestMethod.POST)
    public ResponseBody<Boolean> connectProgram(@RequestBody ConnectReq connectReq) {
        try {
            processManageService.connectProgram(connectReq);
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
        return ResponseBody.success(Boolean.TRUE);
    }

    /**
     * 机床列表
     *
     * @return
     */
    @RequestMapping(value = "/qryMachineToolList", method = RequestMethod.POST)
    public ResponseBody qryMachineToolList(@RequestBody QryMachineToolReq machineToolReq) {
        return ResponseBody.success(processManageService.qryMachineToolList(machineToolReq));
    }


    @RequestMapping(value = "/qryMachineToolChildrenList", method = RequestMethod.POST)
    public ResponseBody qryMachineToolChildrenList(@RequestBody MachineToolChildReq machineToolChildReq) {
        return ResponseBody.success(processManageService.qryMachineToolChildrenList(machineToolChildReq));
    }

    /**
     * 任务分配
     *
     * @return
     */
    @RequestMapping(value = "/taskAllocation", method = RequestMethod.POST)
    @Log(title = "任务分配", businessType = BusinessType.INSERT)
    public ResponseBody<Boolean> taskAllocation(@RequestBody AllocationReq allocationReq) {
        try {
            processManageService.taskAllocation(allocationReq);
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
        return ResponseBody.success(Boolean.TRUE);
    }

    /**
     * 任务分配
     *
     * @return
     */
    @RequestMapping(value = "/changeCraftParams", method = RequestMethod.POST)
    public ResponseBody<Boolean> changeCraftParams() {
            processManageService.changeCraftParams();
        return ResponseBody.success(Boolean.TRUE);
    }

    /**
     * 删除任务分配
     *
     * @return
     */
    @RequestMapping(value = "/deleteTask", method = RequestMethod.POST)
    @Log(title = "任务删除", businessType = BusinessType.DELETE)
    public ResponseBody<Boolean> deleteTask(@RequestBody DeleteTaskReq deleteTaskReq) {
        processManageService.deleteTask(deleteTaskReq);
        return ResponseBody.success(Boolean.TRUE);
    }


    /**
     * 任务分配人员排班查询接口
     *
     * @return
     */
    @RequestMapping(value = "/qryAllotEmployee", method = RequestMethod.POST)
    public ResponseBody<String> qryAllotEmployee(@RequestBody QryAllotEmployeeReq qryAllotEmployeeReq) {
        return ResponseBody.success(processManageService.qryAllotEmployee(qryAllotEmployeeReq));
    }

    /**
     * 任务分配人员排班查询接口(全部)
     *
     * @return
     */
    @RequestMapping(value = "/checkAllotEmployee", method = RequestMethod.POST)
    public ResponseBody checkAllotEmployee(@RequestBody CheckAllotEmployeeReq checkAllotEmployeeReq) {
        return ResponseBody.success(processManageService.checkAllotEmployee(checkAllotEmployeeReq));
    }

    /**
     * 任务分配人员查询接口
     *
     * @return
     */
    @RequestMapping(value = "/checkAllotEmployeeGroup", method = RequestMethod.POST)
    public ResponseBody checkAllotEmployeeGroup(@RequestBody CheckAllotEmployeeGroupReq checkAllotEmployeeGroupReq) {
        return ResponseBody.success(processManageService.checkAllotEmployeeGroup(checkAllotEmployeeGroupReq));
    }

    /**
     * 新增或编辑任务分配人员排班
     *
     * @return
     */
    @RequestMapping(value = "/addOrEditAllotEmployee", method = RequestMethod.POST)
    @Log(title = "新增或编辑任务分配人员排班", businessType = BusinessType.OTHER)
    public ResponseBody addOrEditAllotEmployee(@RequestBody AllotEmployeeEntity allotEmployeeEntity) {
        return ResponseBody.success(processManageService.addOrEditAllotEmployee(allotEmployeeEntity));
    }

    /**
     * 删除任务分配人员排班
     *
     * @return
     */
    @RequestMapping(value = "/deleteAllotEmployee", method = RequestMethod.GET)
    @Log(title = "删除任务分配人员排班", businessType = BusinessType.DELETE)
    public ResponseBody deleteAllotEmployee(@RequestParam("id") Integer id) {
        return ResponseBody.success(processManageService.deleteAllotEmployee(id));
    }

    /**
     * 删除任务分配人员排班
     *
     * @return
     */
    @RequestMapping(value = "/allotEmployeeChart", method = RequestMethod.POST)
    public ResponseBody allotEmployeeChart(@RequestBody AllotEmployeeChartReq allotEmployeeChartReq) {
        return ResponseBody.success(processManageService.allotEmployeeChart(allotEmployeeChartReq));
    }

    /**
     * 查询工序内码
     *
     * @return
     */
    @RequestMapping(value = "/qryProcessCode", method = RequestMethod.GET)
    public ResponseBody qryProcessCode(@RequestParam String processNum,
                                       @RequestParam Integer seq) {
        return ResponseBody.success(processManageService.qryProcessCode(processNum, seq));
    }

    /**
     * 查询程序内码
     *
     * @return
     */
    @RequestMapping(value = "/qryProgramCode", method = RequestMethod.GET)
    public ResponseBody qryProgramCode(@RequestParam String programNum) {
        return ResponseBody.success(processManageService.qryProgramCode(programNum));
    }


    /**
     * 机床任务列表
     *
     * @return
     */
    @RequestMapping(value = "/queryEquipmentTaskList", method = RequestMethod.POST)
    public ResponseBody queryEquipmentTaskList(@RequestBody QueryEquipmentTaskListReq queryEquipmentTaskListReq) {
        return ResponseBody.success(processManageService.queryEquipmentTaskList(queryEquipmentTaskListReq));
    }

    /**
     * 机床任务列表
     *
     * @return
     */
    @RequestMapping(value = "/queryEquipmentTaskListReload", method = RequestMethod.POST)
    public ResponseBody queryEquipmentTaskListReload(@RequestBody QueryEquipmentTaskLReqReload queryEquipmentTaskLReqReload) {
        return ResponseBody.success(processManageService.queryEquipmentTaskListReload(queryEquipmentTaskLReqReload));
    }

    /**
     * 查询单个工序
     *
     * @param figureNo figureNo
     * @param version  version
     * @return
     */
    @RequestMapping(value = "/querySingleProcess", method = RequestMethod.GET)
    public ResponseBody<String> querySingleProcess(@RequestParam("figureNo") String figureNo, @RequestParam("version") Integer version) {
        try {
            return ResponseBody.success(processManageService.querySingleProcess(figureNo, version));
        } catch (ToolManageException toolManageException) {
            return ResponseBody.error(toolManageException.getCode(), toolManageException.getMsg());
        }
    }

    /**
     * 查询工单工序子表
     *
     * @return
     */
    @RequestMapping(value = "/getMachineToolOrderDetail", method = RequestMethod.GET)
    public ResponseBody getMachineToolOrderDetail(@RequestParam String taskId) {
        try {
            return ResponseBody.success(processManageService.getMachineToolOrderDetail(taskId));
        } catch (ToolManageException toolManageException) {
            return ResponseBody.error(toolManageException.getCode(), toolManageException.getMsg());
        }
    }

    @RequestMapping(value = "/pucAndProConnect", method = RequestMethod.POST)
    @Log(title = "产品关联工艺", businessType = BusinessType.OTHER)
    @Permission(title = "产品关联工艺" , permissions = {"pucAndPro.connect"})
    public ResponseBody pucAndProConnect(@RequestBody PucAndProConnectReq pucAndProConnectReq) {
        return ResponseBody.success(processManageService.pucAndProConnectReq(pucAndProConnectReq));
    }

    @RequestMapping(value = "/abutmentProcess", method = RequestMethod.GET)
    public ResponseBody abutmentProcess(@RequestParam("processNum") String processNum) {
        AbutmentProcessContext abutmentProcessContext = new AbutmentProcessContext(zccAbutmentProcessStrategy);
        abutmentProcessContext.abutmentProcess(processNum);
        return ResponseBody.success();
        //return  ResponseBody.success(processManageService.abutmentProcess(processNum));
    }

    /**
     * 程序看板导入
     *
     * @param file
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/importAllotEmployee", method = RequestMethod.POST)
    @Log(title = "导入人员排班信息", businessType = BusinessType.OTHER)
    public ResponseBody<Boolean> importAllotEmployee(@RequestPart("file") MultipartFile file,
                                                     @RequestParam("date") String date,
                                                     HttpServletRequest httpServletRequest) {
        try {
            AllotEmployeeReadListener allotEmployeeReadListener = new AllotEmployeeReadListener();
            FileUploadUtil.checkCommonFile(file);
            EasyExcel.read(file.getInputStream(), AllotEmployeeImport.class, allotEmployeeReadListener).headRowNumber(3).autoCloseStream(true).sheet().doRead();
            processManageService.importAllotEmployee(allotEmployeeReadListener.getImportData(), date);
        } catch (IOException ex) {
            log.error("importOrder error========》", ex);
        } catch (SystemException systemException) {
            log.error("importOrder error========》msg：{}", systemException.getMsg());
            return ResponseBody.error(systemException.getCode(), systemException.getMsg());
        } catch (IllegalAccessException e) {
            log.error("importOrder error========》", e.getMessage());
            return ResponseBody.error("1001", "解析错误1");
        } catch (ParseException e) {
            log.error("importOrder error========》", e.getMessage());
            return ResponseBody.error("1002", "解析错误2");
        }
        return ResponseBody.success(Boolean.TRUE);
    }

    @RequestMapping(value = "/queryMachineToolTaskDetail", method = RequestMethod.GET)
    public ResponseBody queryMachineToolTaskDetail(@RequestParam("id") Integer id) {
        return ResponseBody.success(processManageService.queryMachineToolTaskDetail(id));
    }

    @RequestMapping(value = "/queryMachineToolTasks", method = RequestMethod.POST)
    public ResponseBody queryMachineToolTasks(@RequestBody QueryMachineToolTasksReq queryMachineToolTasksReq) {
        return ResponseBody.success(processManageService.queryMachineToolTasks(queryMachineToolTasksReq));
    }

    @RequestMapping(value = "/qryMachineToolStatusHistory", method = RequestMethod.POST)
    public ResponseBody qryMachineToolStatusHistory(@RequestBody HistoryStatusReq historyStatusReq) {
        return ResponseBody.success(processManageService.qryMachineToolStatusHistory(historyStatusReq));
    }

    @RequestMapping(value = "/editMachineToolStatusBz", method = RequestMethod.GET)
    @Log(title = "编辑机床状态备注", businessType = BusinessType.UPDATE)
    public ResponseBody editMachineToolStatusBz(@RequestParam("id") Integer id, @RequestParam("bz") String bz) {
        return ResponseBody.success(processManageService.editMachineToolStatusBz(id, bz));
    }

    @RequestMapping(value = "/operateActualTime", method = RequestMethod.GET)
    @Log(title = "编辑任务实际开始以及实际结束时间", businessType = BusinessType.UPDATE)
    public ResponseBody operateActualTime(@RequestParam("id") Integer id,
                                          @RequestParam("type") Integer type) {
        return ResponseBody.success(processManageService.operateActualTime(id, type));
    }

    @RequestMapping(value = "/editActualTime", method = RequestMethod.POST)
    @Log(title = "编辑任务实际开始以及实际结束时间", businessType = BusinessType.UPDATE)
    public ResponseBody editActualTime(@RequestBody EditActualTimeReq editActualTimeReq) {
        return ResponseBody.success(processManageService.editActualTime(editActualTimeReq));
    }

    /**
     * 导出工艺excel模版
     *
     * @param response
     */
    @RequestMapping(value = "/exportProcessTemplate", method = RequestMethod.GET)
    public void exportProcessTemplate(HttpServletResponse response) {
        processManageService.exportProcessTemplate(response);
    }

    /**
     * 导入产品excel模版
     */
    @RequestMapping(value = "/importProcessTemplate", method = RequestMethod.POST)
    public ResponseBody importProcessTemplate(@RequestPart("file") MultipartFile file) {
//        List<String> batchadd = FileUtils.batchadd(file);
//        if (CollectionUtil.isNotEmpty(batchadd)) {
//            batchadd.forEach(s -> {
//                ProductionReadListener easyExcelListener = new ProductionReadListener();
//                ExcelReader excelReader = null;
//                try {
//                    //excelReader = EasyExcelFactory.read(file.getInputStream(), easyExcelListener).build();
//                    excelReader = EasyExcelFactory.read(new FileInputStream(s), easyExcelListener).build();
//                    List<ReadSheet> sheets = excelReader.excelExecutor().sheetList();
//                    Map<Integer, List<LinkedHashMap>> sheetInfos = new HashMap<>(sheets.size());
//                    for (ReadSheet sheet : sheets) {
//                        Integer sheetNo = sheet.getSheetNo();
//                        excelReader.read(sheet);
//                        sheetInfos.put(sheetNo, easyExcelListener.getListMap());
//                    }
//                    //最终数据
//                    List<LinkedHashMap> mapList = sheetInfos.get(0);
//                } catch (IOException e) {
//                    log.error("10001", "解析失败");
//                }
//            });
//        }
        List<List<LinkedHashMap>> dataList = CommonUtil.uploadZipFile(file);
        processManageService.importProcessTemplate(dataList);
        return ResponseBody.success();

    }


    @RequestMapping(value = "/confirmTask", method = RequestMethod.GET)
    @Log(title = "确认任务状态", businessType = BusinessType.UPDATE)
    public ResponseBody confirmTask(@RequestParam("id") Integer id,
                                    @RequestParam("confirmFlag") Integer confirmFlag) {
        return ResponseBody.success(processManageService.confirmTask(id, confirmFlag));
    }


}
